package cn.sc.summer.gateway.config;

import cn.sc.summer.constant.factory.YamlPropertySourceFactory;
import cn.sc.summer.gateway.properties.GatewayRouteConfigProperties;
import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.http.codec.ServerCodecConfigurer;
import org.springframework.web.context.request.RequestContextListener;

import javax.annotation.Resource;
import java.util.Properties;

/**
 * 类名：将configService交由spring管理
 *
 * @author a-xin
 * @date 2023/12/7 16:24
 */
@Configuration
@PropertySource(value = "classpath:/summer-gateway.yml", factory = YamlPropertySourceFactory.class)
public class GatewayServiceConfig {

    @Resource
    private GatewayRouteConfigProperties configProperties;

    @Resource
    private NacosConfigProperties nacosConfigProperties;

    @Bean
    public ConfigService configService() throws NacosException {
        Properties properties = new Properties();
        properties.setProperty(PropertyKeyConst.SERVER_ADDR, nacosConfigProperties.getServerAddr());
        properties.setProperty(PropertyKeyConst.NAMESPACE, configProperties.getNamespace());
        return NacosFactory.createConfigService(properties);
    }

    @Bean
    public ServerCodecConfigurer serverCodecConfigurer() {
        return ServerCodecConfigurer.create();
    }

    @Bean
    public RequestContextListener requestContextListener() {
        return new RequestContextListener();
    }

}

